package fr.labri.buganalyzer.eclipse;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig;

public final class VcsBugtrackerMapping {

	private static final String FOLDER_PATH = "resources/testData/";
	private static final String ECLIPSE_TRACKER_URL = "https://bugs.eclipse.org/bugs/buglist.cgi";
	private static final String ECLIPSE_PRODUCT_TOKKEN = "?product=";
	private static final String ECLIPSE_COMPONENT_TOKKEN = "&component=";

	private Map<String, List<String>> repos;
	private Map<String, List<String>> bugtracker;
	private List<Map<String, List<String>>> mapping;

	private VcsBugtrackerMapping() {
		this.repos = new HashMap<>();
		this.bugtracker = new HashMap<>();
	}

	@SuppressWarnings("unchecked")
	private void load() {
		ObjectMapper mapper = new ObjectMapper();
		try {
			repos = mapper.readValue(new File(FOLDER_PATH, "NewEclipseGitRepos.json"), repos.getClass());
			bugtracker = mapper.readValue(new File(FOLDER_PATH, "EclpiseProjectsInBugzilla.json"), bugtracker.getClass());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private void mapVcs2Btracker() {
		// put the vcsClones (vcs urls for the same products) with the trackers url (trackers for different parts of the product)
		mapping = new ArrayList<Map<String, List<String>>>(); 
		for (Entry<String, List<String>> entry : repos.entrySet()) {
			createMappingEntry(entry);
		}
	}

	private void createMappingEntry(Entry<String, List<String>> entry) {
		// stores one entry of the mapping list
		Map<String, List<String>> mappingEntry;
		// stores the vcsClones
		List<String> vcsClones = new ArrayList<String>();
		mappingEntry = new HashMap<String, List<String>>();
		for (String vcsUrl : entry.getValue()) {
			for (String tracker : bugtracker.keySet()) {
				if (vcsUrl.toUpperCase().contains(tracker.toUpperCase())) {
					vcsClones.addAll(entry.getValue());
					List<String> trackerUrls = new ArrayList<>();
					for (String comp : bugtracker.get(tracker)) {
						String url = ECLIPSE_TRACKER_URL + ECLIPSE_PRODUCT_TOKKEN + tracker + ECLIPSE_COMPONENT_TOKKEN + comp;
						trackerUrls.add(url);
					}
					mappingEntry.put("vcs", vcsClones);
					mappingEntry.put("tracker", trackerUrls);
//					if (vcsClones.size() == 1)
						mapping.add(mappingEntry);
					return;
				}
			}
		}
	}

	private void writeToJsonFile() throws IOException {
		ObjectMapper mapper = new ObjectMapper();
		mapper.configure(SerializationConfig.Feature.INDENT_OUTPUT, true);
		mapper.writeValue(new File(FOLDER_PATH + "Mapping.json"), mapping);
	}

	public static void main(String[] args) throws IOException {
		VcsBugtrackerMapping o = new VcsBugtrackerMapping();
		o.load();
		o.mapVcs2Btracker();
		o.writeToJsonFile();
	}
}
